<template>
  <!-- 族谱列表 -->
  <div v-show="vMode === 'home'">
    <van-nav-bar title="族谱管理" left-text="返回" left-arrow @click-left="goHome" />
    <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="() => loadList()">
      <van-cell v-for="item in vList" :key="item.id"
        :label="`人数：${item.member_counter}，最近更新： ${item.last_mtime}，创建者 ${item.cuser}`" @click="clanView(item)"
        icon="friends-o" is-link>
        <template #title>
          <span class="custom-title">{{ item.clan }}</span>
          <van-tag type="success" v-if="item.is_admin === 1">管理员</van-tag>
          <van-tag type="primary" v-if="item.is_admin === 0">观察员</van-tag>
        </template>
      </van-cell>
    </van-list>
  </div>
  <!-- 族谱详情 -->
  <div v-show="vMode === 'view'">
    <van-nav-bar :title="viewRow.clan" left-text="返回" left-arrow @click-left="vMode = 'home'" @click-right="
      view.mode = 'edit';
    editRow = {};
    viewRow.clan = '新增族谱';
    " fixed>
      <template #right>
        <van-icon name="add-o" size="18" />
      </template>
    </van-nav-bar>
    <p style="margin-top: 40px"></p>
    <!-- 族谱详情 -->
    <div v-show="view.mode === 'view'">
      <van-cell title="名称" :value="viewRow.clan" />
      <van-cell title="简介" :label="viewRow.brief" />
      <van-cell title="备注" :label="viewRow.remark" />
      <van-cell title="创建时间" :label="viewRow.ctime" />
      <div style="margin: 16px; text-align: right" v-if="viewRow.is_admin">
        <van-button round type="primary" size="small" @click="onEdit">修改</van-button>
        <van-button round type="danger" size="small" @click="onDelete">删除</van-button>
      </div>
    </div>
    <!-- 编辑 -->
    <div v-show="view.mode === 'edit'">
      <van-form @submit="onSubmit">
        <van-field v-model="editRow.clan" name="clan" label="名称" placeholder="名称"
          :rules="[{ required: true, message: '请填写名称' }]" clearable />
        <van-field name="public_mk" label="公开">
          <template #input>
            <van-switch v-model="editRow.public_mk" size="20" />
          </template>
        </van-field>
        <van-field v-model="editRow.brief" name="brief" rows="5" autosize label="简介" type="textarea" placeholder="请输入简介"
          clearable />
        <van-field v-model="editRow.remark" name="remark" rows="2" autosize label="备注" type="textarea" clearable />
        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
    </div>
    <!-- 其他 -->
    <div v-show="view.mode === 'other'">
      <van-cell title="用户列表" v-if="viewRow.is_admin" is-link />
    </div>
    <van-tabbar route>
      <van-tabbar-item replace icon="home-o" @click="view.mode = 'view'">
        族谱</van-tabbar-item>
      <van-tabbar-item replace icon="user-o" :to="`/clan/tree/${viewRow.id}`">族人</van-tabbar-item>
      <!-- 待实现 -->
      <!-- <van-tabbar-item
        replace
        name="setting"
        icon="fire-o"
        :to="`/record/${viewRow.id}`"
        >纪事</van-tabbar-item
      > -->
      <van-tabbar-item replace name="setting" icon="fire-o">纪事</van-tabbar-item>
      <van-tabbar-item replace icon="ellipsis" @click="view.mode = 'other'">其他</van-tabbar-item>
    </van-tabbar>
  </div>
</template>
<script lang="ts" setup>
import {
  showConfirmDialog,
  showFailToast,
  showLoadingToast,
  showSuccessToast,
} from "vant";
import { Wap } from "../../../common/wap";
import { useRoute } from "vue-router";
import { onMounted, ref } from "vue";
import type { Ref } from "vue";

// 路由
const route = useRoute();
const params = route.params;

// 系统变量
const clanId = ref(params.clan_id);
const vList: Ref<Array<KvObj>> = ref([]); // 数据列表
const loading = ref(false);
const finished = ref(false);
const vMode = ref(clanId.value ? "view" : "home");
const viewRow: Ref<KvObj> = ref({}); //查看视图模型[数据]
const editRow: Ref<KvObj> = ref({}); //编辑数据（可用于新增）
const view: Ref<KvObj> = ref({
  mode: "view", //查看内部模型
});
const paginate = ref({
  current: 1,
  pageSize: 15,
});

function goHome() {
  location.href = "./index.html#/user";
}

// 数据列表加载
function loadList(postData?: KvObj | null, flushMk?: boolean) {
  if (flushMk) {
    paginate.value.current = 1;
  }
  postData = postData || {};
  postData = Object.assign({}, paginate.value, postData);
  Wap.post("/square/data/clan", postData)
    .then((result) => {
      if (result.status === "ok") {
        const data = result.data;
        let list = data.list || [];
        let oData = vList.value;
        if (!list || list.length === 0) {
          finished.value = true;
          loading.value = false;
        } else {
          loading.value = false;
          finished.value = false;
        }
        if (!flushMk) {
          list = oData.concat(list);
        }
        vList.value = list;
      } else {
        showFailToast(result.msg);
      }
      finished.value = true;
      loading.value = false;
    })
    .catch((error) => {
      console.log(error);
      finished.value = true;
    });
}

function clanView(item: KvObj) {
  vMode.value = "view";
  view.value.mode = "view";
  viewRow.value = item;
}

function onDelete() {
  showConfirmDialog({
    title: "提示",
    message: "您确定要删除数据吗，删除后不可撤销？",
  }).then(() => {
    // on confirm
    let loading = showLoadingToast({
      duration: 0, // 持续展示 toast
      forbidClick: true,
      message: "数据提交中",
    });
    Wap.post("/square/data/clan/del", { id: viewRow.value.id })
      .then((result) => {
        Wap.resolveResponse(result)
          .then(() => {
            loadList(null, true);
            showSuccessToast(result.msg);
            vMode.value = "home";
          })
          .catch((msg) => {
            showFailToast(msg);
          });
      })
      .finally(() => {
        loading.close();
      });
  });
}

function onSubmit(values: KvObj) {
  let postData = Object.assign({}, editRow.value, values);
  postData["public_mk"] = !!postData["public_mk"];
  let loading = showLoadingToast({
    duration: 0, // 持续展示 toast
    forbidClick: true,
    message: "数据提交中",
  });
  Wap.post("/square/data/clan/save", postData)
    .then((result) => {
      Wap.resolveResponse(result)
        .then(() => {
          showSuccessToast("数据保存成功！");
          vMode.value = "home";
          loadList(null, true);
        })
        .catch((msg) => {
          //showFailToast(msg);
          console.log(msg ? msg : "程序错误未能正确抛出异常");
        });
    })
    .finally(() => {
      loading.close();
    });
}

function onEdit() {
  view.value.mode = "edit";
  let row: KvObj = viewRow.value;
  row.public_mk = !!row.public_mk;
  editRow.value = row;
}

onMounted(function () {
  if (clanId.value) {
    Wap.get(`/square/data/clan?clan_id=${clanId.value}`).then((result) => {
      Wap.resolveResponse(result)
        .then((data) => {
          viewRow.value = data;
        })
        .catch((msg) => {
          showFailToast(msg);
        });
    });
  }
});
</script>